package com.imufe.chemicalenterprisedangerwarning.service.impl;

import com.baomidou.mybatisplus.core.conditions.query.LambdaQueryWrapper;
import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.imufe.chemicalenterprisedangerwarning.entity.po.RegionPO;
import com.imufe.chemicalenterprisedangerwarning.entity.query.RegionQuery;
import com.imufe.chemicalenterprisedangerwarning.entity.vo.RegionDetailedVO;
import com.imufe.chemicalenterprisedangerwarning.entity.vo.RegionVO;
import com.imufe.chemicalenterprisedangerwarning.mapper.RegionMapper;
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import com.imufe.chemicalenterprisedangerwarning.service.RegionService;
import com.imufe.chemicalenterprisedangerwarning.util.BeanUtils;
import com.imufe.chemicalenterprisedangerwarning.util.ListUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;

import java.util.LinkedList;
import java.util.List;
import java.util.stream.Collectors;

/**
 * <p>
 * 服务实现类
 * </p>
 *
 * @author BaiBan
 * @since 2022-09-20
 */
@Service
public class RegionServiceImpl extends ServiceImpl<RegionMapper, RegionPO> implements RegionService {

    @Autowired
    RegionMapper mapper;

    @Override
    public RegionDetailedVO detailed(Long id) {
        List<String> regionList = new LinkedList<>();
        RegionPO po = mapper.selectById(id);
        RegionDetailedVO vo = new RegionDetailedVO();
        vo.setId(id);
        // 循环获取上级区域插入list头部
        while (po != null) {
            regionList.add(0, po.getName());
            po = mapper.selectById(po.getSuperId());
        }

        vo.setFullName(String.join("", regionList));
        return vo;
    }

    @Override
    public List<RegionVO> regionList(Long id) {

        LambdaQueryWrapper<RegionPO> qw = new LambdaQueryWrapper<>();
        if (id == null)
            qw.isNull(RegionPO::getSuperId);
        else
            qw.eq(RegionPO::getSuperId, id);

        List<RegionPO> list = mapper.selectList(qw);
        return ListUtils.copyList(list, RegionVO.class);
    }

    @Override
    public RegionVO create(RegionQuery query) {
        RegionPO po = BeanUtils.copyPOJO(query, RegionPO.class);
        mapper.insert(po);
        return BeanUtils.copyPOJO(po, RegionVO.class);
    }
}